package com.ybxiang.camera_opengl.filter

import android.content.Context
import android.opengl.GLES20
import com.ybxiang.camera_opengl.R
import com.ybxiang.camera_opengl.utils.OpenGLUtils
import com.ybxiang.camera_opengl.utils.OpenGLUtils.TEXTURE
import com.ybxiang.camera_opengl.utils.OpenGLUtils.VERTEX
import java.nio.ByteBuffer
import java.nio.ByteOrder
import java.nio.FloatBuffer

/**
 * Created by yunbo.xiang on 2021/12/15
 * Describe:camera滤镜
 */
class CameraFilter(context: Context) {
    private var vPosition: Int = 0
    private var vCoord: Int = 0
    private var vTexture: Int = 0
    private var vMatrix: Int = 0
    private var program: Int = 0
    private var vertexBuffer: FloatBuffer
    private var textureBuffer: FloatBuffer

    init {
        val vertexShader = OpenGLUtils.readRawTextFile(context, R.raw.camera_vert)
        val fragShader = OpenGLUtils.readRawTextFile(context, R.raw.camera_frag)
        program = OpenGLUtils.loadProgram(vertexShader, fragShader)
        GLES20.glUseProgram(program)

        // 获取程序组的变量 索引
        vPosition = GLES20.glGetAttribLocation(program, "vPosition")
        vCoord = GLES20.glGetAttribLocation(program, "vCoord")
        vTexture = GLES20.glGetUniformLocation(program, "vTexture")
        vMatrix = GLES20.glGetUniformLocation(program, "vMatrix")

        // 坐标
        vertexBuffer = ByteBuffer.allocateDirect(VERTEX.size * 4)
            .order(ByteOrder.nativeOrder())
            .asFloatBuffer()
        vertexBuffer.clear()
        vertexBuffer.put(VERTEX)

        // 纹理
        textureBuffer = ByteBuffer.allocateDirect(TEXTURE.size * 4)
            .order(ByteOrder.nativeOrder())
            .asFloatBuffer()
        textureBuffer.clear()
        textureBuffer.put(TEXTURE)

    }

    fun onDraw(mtx: FloatArray, textureId: Int) {
        // 传递顶点坐标 顶点坐标：确定形状
        vertexBuffer.position(0)
        GLES20.glVertexAttribPointer(vPosition, 2, GLES20.GL_FLOAT, false, 0, vertexBuffer)
        GLES20.glEnableVertexAttribArray(vPosition)

        // 传递纹理坐标 纹理坐标：如何贴图，上颜色
        textureBuffer.position(0)
        GLES20.glVertexAttribPointer(vCoord, 2, GLES20.GL_FLOAT, false, 0, textureBuffer)
        GLES20.glEnableVertexAttribArray(vCoord)

        // 相当于激活一个用来显示图片的画框
        GLES20.glActiveTexture(GLES20.GL_TEXTURE)
        GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, textureId)
        GLES20.glUniform1i(vTexture, 0)

        GLES20.glUniformMatrix4fv(vMatrix, 1, false, mtx, 0)

        // 通知画画
        // 三角形
        GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, 0, 4)
        GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, 0)
    }

    fun release() {
        GLES20.glDeleteProgram(program)
    }
}